package demo.client;

import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class MinaClient01 {
	private static Logger logger = Logger.getLogger(MinaClient01.class);
	private static String HOST = "192.168.9.94";
	private static int PORT = 6950;

	public static void main(String[] args) throws InterruptedException {
		// 创建一个非阻塞的客户端程序
		IoConnector connector = new NioSocketConnector(); // 创建连接
		// 设置链接超时时间
		// connector.setConnectTimeout(30000);
		connector.setConnectTimeoutMillis(30000);
		// 添加过滤器
		connector.getFilterChain().addLast(
				// 添加消息过滤器
				"codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS
						.getValue(), LineDelimiter.WINDOWS.getValue())));
		// new ProtocolCodecFilter(new MyTextLineCodecFactory()));
		// 添加客户端业务逻辑处理器类
		connector.setHandler(new Demo1ClientHandler());// 添加业务处理
		IoSession session = null;
		for (int i = 30001; i < 35000; i++) {
			try {
				ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT));// 创建连接
				// 创建过程是异步的，就是不用管创建是否成功，下面继续执行，
				// 但是因为下面这句，使创建成功后再接着执行future.getSession();这样异步转为同步
				future.awaitUninterruptibly();// 等待连接创建完成
				session = future.getSession();// 获得session
				String packages = "#Ai+333," + i + ",Fir,B" + i + "!";
				session.write(packages);// 发送消息到服务器
				logger.info("客户端发送信息到服务器");
			} catch (Exception e) {
				logger.error("客户端链接异常...", e);
			}
			// session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
			// connector.dispose();
			// 停止客户端主线程,jvm未退出(进程中的javaw.exe还存在),
			// iosession中的close方法只是关闭了TCP的连接通道
			Thread.sleep(500);
		}
	}
}
